#include "board_config.h"
#include "board_uart.h"
#include "ADIS16405.h"
#include "platform.h"
#include <stdio.h>

extern TIM_HandleTypeDef trigger_tim_handler;
static uint64_t systime_ms = 0;
extern struct event_queue event_queue;

struct adis16405_raw adis_data_raw;
uint8_t adis_byte_raw[ADIS16405_BURST_READ_LEN] = {0};

/**
 * @brief  Period elapsed callback in non blocking mode
 * @param  htim: TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim == &trigger_tim_handler) {
		systime_ms++;
		board_led_toggle(0);
		board_stdout_flush();

		if (HAL_SPI_GetState(&spi1handler) == HAL_SPI_STATE_READY) {
			spi_select(SPI_ADIS16405, 1);
			adis16405_start_burst_reading(&spi1handler, adis_byte_raw);
		}
		printf("loop end\r\n");
	}
}

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef* hspi)
{
	if (hspi == &spi1handler) {
		spi_select(SPI_ADIS16405, 0);
		adis16405_byte2raw(&adis_data_raw, adis_byte_raw);
		event_post(&event_queue, EVENT_IMU_DATA, (void *)(&adis_data_raw));
	}
}

uint64_t board_get_systime()
{
	return systime_ms*1000000/TRIGGER_FREQ + trigger_tim_handler.Instance->CNT;
}

